/**
 * 
 */
package com.airnewslinkosky.ticket.ui.financial;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.airnewslinkosky.ticket.R;
import com.airnewslinkosky.ticket.model.FinancialInfo;
import com.airnewslinkosky.ticket.model.FinancialInfoResult;
import com.airnewslinkosky.ticket.model.Flight;
import com.airnewslinkosky.ticket.model.SearchFinancial;
import com.airnewslinkosky.ticket.net.WebAccessor;
import com.airnewslinkosky.ticket.ui.BaseActivity;
import com.airnewslinkosky.ticket.ui.Main;
import com.airnewslinkosky.ticket.ui.client.ClientSearch;
import com.airnewslinkosky.ticket.util.AddrUtil;
import com.airnewslinkosky.ticket.util.Constants;
import com.airnewslinkosky.ticket.util.FlyUtil;
import com.mobclick.android.MobclickAgent;

/**
 * @author CX
 *
 */
public class FinancialList extends BaseActivity implements AdapterView.OnItemClickListener, OnClickListener {
	
	/** 是否需要更新数据，从详细页面返回时需要更新数据 */
	public static boolean UPDATE_INDICATOR = false;
	
	public final int NORESULT = 1;
	public final int SEARCH_ERROR=2;
	public final int SUCCESS=3;
	public final int ORDER_TIME = 4;
	public final int ORDER_PRICE = 5;
	
	public static List<FinancialInfo> financialList = new ArrayList<FinancialInfo> ();
	
	public SimpleAdapter sa;
	
	private final static int DATE_DIALOG = 0;
	private final static int TIME_DIALOG = 1;
	
	List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
	
	private TextView orderScoll, btn_returnInput, bookOrderType, orderTimeStart, orderTimeEnd;
	private ListView orderList;
	private Button btnByTime, btnByPrice;
	
	private Button backBut;
	
	String[] selectOptionList = null;
	
	private Calendar c = null;
	
	private ProgressDialog progressDialog = null;
	
	private SearchFinancial searchFinancial;
	
	private AddrUtil addrUtil;
	
	private FlyUtil flyUtil;
	
	private SharedPreferences sp;
	private String loginNameRe = "";
	private String isLoninOK = null;//是否登录
	private String autoLogin = null;//记着登录
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.financial_list);
		
		activityList.add(this); 
		
		backBut = (Button) findViewById(R.id.backBut);
		backBut.setOnClickListener(clickListener);
		
		sp = getSharedPreferences("UserInfoB2B", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
		
		searchFinancial = (SearchFinancial)getIntent().getSerializableExtra("searchFinancial");
		
		orderList = (ListView) findViewById(R.id.orderList);
		orderList.setOnItemClickListener(this);
		
//		btnByTime = (Button) findViewById(R.id.btn_byTime);
//		btnByTime.setOnClickListener(clickListener);
//		btnByPrice = (Button) findViewById(R.id.btn_byPrice);
//		btnByPrice.setOnClickListener(clickListener);
		
		findViewById(R.id.btn_reflush).setOnClickListener(clickListener);
//		findViewById(R.id.btn_enqury).setOnClickListener(clickListener);
		
		//初始化地址参数
		addrUtil = new AddrUtil(this);
		//初始化航空参数
		flyUtil = new FlyUtil(this);
		
		//renderData();
		if (financialList.isEmpty()) {
			search();
		} else {
			renderData();
		}
	}
	
//	@Override
//    protected void onResume() {
//    	super.onResume();
//    	//回到后重新下载
//    	if (UPDATE_INDICATOR) {
//    		search();
//    		UPDATE_INDICATOR = false;
//    	}
//    }
	
    
	OnClickListener clickListener= new OnClickListener() { 
    	public void onClick(View v) { 
    		switch (v.getId()) {
    		case R.id.btn_byTime: {
    			Log.i("OrderList", "btn_byTime");
    			//调用
				Message msg = new Message();
				msg.what = ORDER_TIME;
				myHandler.sendMessage(msg);
    			break;
    		}
    		case R.id.btn_byPrice: {
    			Log.i("OrderList", "btn_byPrice");
    			//排序
    			Message msg = new Message();
				msg.what = ORDER_PRICE;
				myHandler.sendMessage(msg);
    			break;
    		}
    		case R.id.backBut: {
    			Intent intent = new Intent(FinancialList.this, FinancialSearch.class);
    			FinancialList.UPDATE_INDICATOR = true;
    			startActivity(intent);
    			break;
    		}
    		case R.id.btn_reflush: {
    			search();
    			break;
    		}
    		case R.id.btn_enqury: {
    			Intent intent = new Intent(FinancialList.this, FinancialSearch.class);
    			startActivity(intent);
    		}
    		default:
    			break;
    		}
    	}
	};
	
	public void getData(){
		progressDialog = ProgressDialog.show(this, "请稍等...", "查询订单中...",
				true);
		final Thread thread1 = new Thread() {
			public void run() {
				FinancialInfoResult financialInfoResult =  WebAccessor.getFinancialInfo(FinancialList.this, searchFinancial,"","");
				if (progressDialog.isShowing()) {
					if (financialInfoResult== null) {
						Message msg = new Message();
						msg.what = NORESULT;
						myHandler.sendMessage(msg);
					}else if(!"0".equals(financialInfoResult.getRet_Code())){
						Message msg = new Message();
						msg.what = SEARCH_ERROR;
						msg.obj = "";
						myHandler.sendMessage(msg);
					}else  if("0".equals(financialInfoResult.getRet_Code())){
						Message msg = new Message();
						msg.what = SUCCESS;
						msg.obj = financialInfoResult.getRet_Msg();
						financialList = financialInfoResult.getFinancialInfoList();
						myHandler.sendMessage(msg);
					}
					progressDialog.dismiss();
				}
			}
		};
		progressDialog.setCancelable(true);
		thread1.start();
	}
	
	public Handler myHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case NORESULT:
				Toast.makeText(FinancialList.this, "未找到符合条件的订单", Toast.LENGTH_LONG)
						.show();
				data.clear();
				if (sa != null) {
					sa.notifyDataSetChanged();
				}
				break;
			case SEARCH_ERROR:
				Toast.makeText(FinancialList.this, (String)msg.obj, Toast.LENGTH_LONG)
				.show();
				data.clear();
				if (sa != null) {
					sa.notifyDataSetChanged();
				}
				break;
			case SUCCESS:
				renderData();
				break;
			case ORDER_TIME:
				//日期排序
    			Collections.sort(financialList, new Comparator<FinancialInfo>() {
    			      public int compare(FinancialInfo object1,
    			    		  FinancialInfo object2) {
    			    	  	//根据日期倒序排序
//    			    	   String departureTime1 = object1.FlightTicketsList.get(0).DepartureTime;
//    			    	   String departureTime2 = object2.FlightTicketsList.get(0).DepartureTime;
//    			    	   Log.i("OrderList", "departureTime1:"+departureTime1+" departureTime2:"+departureTime2);
//    			    	   if (departureTime1 != "" && departureTime2 != "") {
//    			    		   if (DateUtil.compareTo(departureTime1, departureTime2)) {
//        			    		   return 1;
//        			    	   }
//    			    	   }
    			    	   return -1;
    			      }    
    			     }); 
    			renderData();
				break;
			case ORDER_PRICE:
				//价格排序
    			Collections.sort(financialList, new Comparator<FinancialInfo>() {
    			      public int compare(FinancialInfo object1,
    			    		  FinancialInfo object2) {
    			    	  	//根据价格顺排排序
//    			    	   String cabinPrice1 = object1.FlightTicketsList.get(0).CabinPrice;
//    			    	   String cabinPrice2 = object2.FlightTicketsList.get(0).CabinPrice;
//    			    	   Log.i("OrderList", "cabinPrice1:"+cabinPrice1+" cabinPrice2:"+cabinPrice2);
//    			    	   BigDecimal cabinPrice1Dec = new BigDecimal(cabinPrice1 != "" ? cabinPrice1 : "0");
//    			    	   BigDecimal cabinPrice2Dec = new BigDecimal(cabinPrice2 != "" ? cabinPrice2 : "0");
//    			    	   if (cabinPrice1Dec.compareTo(cabinPrice2Dec) > 0) {
//    			    		   return 1;
//    			    	   } else if (cabinPrice1Dec.compareTo(cabinPrice2Dec) < 0) {
//    			    		   return -1;
//    			    	   }
    			    	   return 0;
    			      }    
    			     }); 
    			renderData();
				break;
			}
			String fcity = getIntent().getStringExtra("fcity");
			String tcity = getIntent().getStringExtra("tcity");
			StringBuffer sb = new StringBuffer().append("   ").append(fcity).append("至").append(tcity);
			//mTitleInfo.setText(sb);
			super.handleMessage(msg);
		}
	};
	
	/**
	 * 展现数据
	 */
	public void renderData(){
		data.clear();
		
		for (int j = 0; j < financialList.size(); j++) {
			FinancialInfo financialInfo = financialList.get(j);
			Map<String, Object> map = new HashMap<String, Object>();
			
			map.put("order_date", financialInfo.getOrderDate());
			map.put("fly_deal_price", financialInfo.getFlyDealPrice());
			map.put("ticket_count", financialInfo.getTicketCount());
			map.put("fly_departure", financialInfo.getFlyDeparture());
			map.put("fly_arrival", financialInfo.getFlyArrival());
			map.put("ticket_no", financialInfo.getTicketNo());
			map.put("passenger", financialInfo.getPassenger());
			map.put("benefits_obtained", financialInfo.getBenefitsObtained());
			map.put("fly_order_no", financialInfo.getFlyOrderNo());
			
			data.add(map);
		}
		
		sa = new SimpleAdapter(this, data, R.layout.financial_list_item, new String[] {
				"order_date", "fly_deal_price", "ticket_no", "fly_departure", 
				"fly_arrival", "passenger", "benefits_obtained", "fly_order_no"},
				new int[] { R.id.order_date, R.id.fly_deal_price, R.id.ticket_no,
						R.id.fly_departure, R.id.fly_arrival, R.id.passenger, 
						R.id.benefits_obtained, R.id.fly_order_no});
		orderList.setAdapter(sa);  
		sa.notifyDataSetChanged();
	}
	
	

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Intent intentR = new Intent();
		intentR.setClass(FinancialList.this, FinancialDetail.class);
		startActivity(intentR);
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
	
	private void search() {
    	final String ticketNoValue = "";
		
		ContentValues values = new ContentValues();
		progressDialog = ProgressDialog.show(this, "请稍等...", "查询帐单中...",true);
		final Thread thread1 = new Thread() {
			public void run() {
//				sp = getSharedPreferences("UserInfoB2B", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
//		        String userIdLogin = sp.getString("userIdB2B", null);
//		        Log.i("OrderSearch userIdLogin", userIdLogin);
//		        String userPwd =  sp.getString("userPwdB2B", null);
//		        Log.i("OrderSearch userPwd", userPwd);
		        
		        String userIdLogin = Constants.USERID;
		        String userPwd =  Constants.USERPWD;
		        String asToken =  Constants.ASToken;
		        
		        FinancialInfoResult financialInfoResult =  WebAccessor.getFinancialInfo(FinancialList.this, searchFinancial,userIdLogin,userPwd);
				
				if (progressDialog.isShowing()) {
					if (financialInfoResult== null) {
						Message msg = new Message();
						msg.what = NORESULT;
						myHandler.sendMessage(msg);
					}else if(!"0".equals(financialInfoResult.getRet_Code())){
						Message msg = new Message();
						msg.what = SEARCH_ERROR;
						msg.obj = financialInfoResult.getRet_Msg();
						myHandler.sendMessage(msg);
					}else{
						FinancialList.financialList = financialInfoResult.getFinancialInfoList();
						//调用
						Message msg = new Message();
						msg.what = SUCCESS;
						msg.obj = financialInfoResult.getRet_Msg();
						myHandler.sendMessage(msg);
					}
					progressDialog.dismiss();
				}
			}
		};
		progressDialog.setCancelable(true);
		thread1.start();
	}
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
	
}
